package vip.zhenzicheng.test.juc.lock;

/**
 * 锁消除
 *
 * @author zhenzicheng
 * @date 2022-09-14 18:27
 */
public class LockClearCase {

  final static Object lock = new Object();

  /**
   * 锁消除
   */
  public void m1() {
    // synchronized (lock) {
    //   System.out.println("----hello LockClear");
    // }
    Object o = new Object();
    // JIT会消除局部变量的锁，每次都是重新创建
    synchronized (o) {
      System.out.println("----helo LockClearCase\t" + o.hashCode() + "\t" + lock.hashCode());
    }
  }

  /**
   * 锁粗化
   */
  public void m2() {
    new Thread(() -> {
      synchronized (lock) {
        System.out.println("11111111");
      }
      synchronized (lock) {
        System.out.println("22222222");
      }
      synchronized (lock) {
        System.out.println("33333333");
      }
      synchronized (lock) {
        System.out.println("44444444");
      }
      // 相当于
      // synchronized (lock) {
      //   System.out.println("11111111");
      //   System.out.println("22222222");
      //   System.out.println("33333333");
      //   System.out.println("44444444");
      // }
    }, "ttt").start();
  }

  public static void main(String[] args) {
    LockClearCase lockClearCase = new LockClearCase();
    for (int i = 0; i < 10; i++) {
      new Thread(() -> {
        // lockClearCase.m1();
        lockClearCase.m2();
      }, String.valueOf(i)).start();
    }
  }
}
